# 给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。
#
#
#
#  示例：
# 二叉树：[3,9,20,null,null,15,7],
#
#      3
#    / \
#   9  20
#     /  \
#    15   7
#
#
#  返回其层次遍历结果：
#
#  [
#   [3],
#   [9,20],
#   [15,7]
# ]
#
#  Related Topics 树 广度优先搜索
#  👍 604 👎 0


# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
from typing import List


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        stack = []
        stack.append(root)
        res = []
        while len(stack) != 0:
            tmp = []
            nextNodes = []
            for treeNode in stack:
                tmp.append(treeNode.val)
                if treeNode.left:
                    nextNodes.append(treeNode.left)
                if treeNode.right:
                    nextNodes.append(treeNode.right)

            del stack[:]
            res.append(tmp)
            stack.extend(nextNodes)
        return res


# leetcode submit region end(Prohibit modification and deletion)

root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(15)
print(Solution().levelOrder(root))


